package at.jku.se.fastsell.db4o;

import java.util.logging.Logger;

import at.jku.se.fastsell.db4o.transactions.Transaction;

import com.db4o.ext.Db4oException;

/**
 * Handler class for db4o database transactions
 */
public class TransactionManager {
	
	private static final Logger LOG = Logger.getLogger(TransactionManager.class.getName());

	public static <T> T run(Transaction<T> transaction) throws DatabaseException {
		try {
			LOG.info("Running transaction '" + transaction.toString() + "'");
			T result = transaction.run();
			// transaction.close();
			LOG.info("Transaction '" + transaction.toString() + "' successful committed.");
			return result;
			// --
		} catch (Db4oException e) {
			LOG.warning("Transaction '" + transaction.toString() + "' failed, starting rollback. Reason: "
					+ e.toString());
			transaction.rollback(); // probably also catch rollback exceptions?
			return retryTransaction(transaction);
		}
	}

	// --------------------------------------------------------------------------------------------

	private static <T> T retryTransaction(Transaction<T> transaction) throws DatabaseException {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}

		try {
			LOG.info("Retrying transaction '" + transaction.toString() + "'");
			T result = transaction.run();
			// transaction.close();
			return result;
			// --
		} catch (Db4oException e) {
			LOG.warning("Transaction '" + transaction.toString() + "' failed again: "
					+ e.getLocalizedMessage());
			throw new DatabaseException("Transaction '" + transaction.toString()
					+ "' failed to run. Reason: " + e.toString(), e);
		}
	}

}
